//
//  NSObject+Common.m
//  ContinueEducation
//
//  Created by 迟建国 on 2018/7/10.
//  Copyright © 2018年 CE. All rights reserved.
//

#import "NSObject+Common.h"
#define kPath_ResponseCache @"XDResponseCache"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <objc/runtime.h>
#import "GloableMacro.h"
#import "AppDelegate.h"

@implementation NSObject (Common)

- (NSString *)dateFormatWithTimeInterval:(NSTimeInterval)time {
    if(time > 140000000000) {
        time = time / 1000;
    }
    NSDate *updatedTime = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    NSString *theDay = [dateFormatter stringFromDate:updatedTime];//日期的年月日
    NSString *currentDay = [dateFormatter stringFromDate:[NSDate date]];//当前年月日
    if ([theDay isEqualToString:currentDay]) {//当天
        [dateFormatter setDateFormat:@"今天 hh:mm"];
        return [dateFormatter stringFromDate:updatedTime];
    } else if ([[dateFormatter dateFromString:currentDay] timeIntervalSinceDate:[dateFormatter dateFromString:theDay]] == 86400) {//昨天
        [dateFormatter setDateFormat:@"昨天 hh:mm"];
        return [dateFormatter stringFromDate:updatedTime];
    } else if ([[dateFormatter dateFromString:currentDay] timeIntervalSinceDate:[dateFormatter dateFromString:theDay]] < 86400 * 7) {//间隔一周内
        [dateFormatter setDateFormat:@"EEEE hh:mm"];
        return [dateFormatter stringFromDate:updatedTime];
    } else {//以前
        [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm"];
        return [dateFormatter stringFromDate:updatedTime];
    }
}

- (NSString *)dateFormatyyyy_MM_dd:(NSTimeInterval)time {
    if(time > 140000000000) {
        time = time / 1000;
    }
    NSDate *updatedTime = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    return [dateFormatter stringFromDate:updatedTime];
}
- (void)showHudTipStr:(NSString *)tipStr{
    [HUDHelper showCustomAlertMessage:tipStr];
}
- (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format?:@"yyyy-MM-dd hh:mm:ss"];
    return [dateFormatter stringFromDate:date];
}

NSString *NSDocumentsFolder(void){
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

NSString *NSCacheFolder(void){
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}


- (void)networkReachability {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSString *trip = @"未知网络";
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                trip = @"未知网络";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                trip = @"WiFi网络";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: {
                CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
                
                if ([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
                    trip = @"4G移动网络";
                }else if([telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [telephonyInfo.currentRadioAccessTechnology  isEqualToString:CTRadioAccessTechnologyGPRS] || [telephonyInfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]){
                    trip = @"2G移动网络";
                }else{
                    trip = @"3G移动网络";
                }
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
                trip = @"没网络";
                break;
            default:
                break;
        }
        if ([trip isEqualToString:@"4G移动网络"] || [trip isEqualToString:@"WiFi网络"]) {
            //网络可用
        }else{
            [self showHudTipStr:[NSString stringWithFormat:@"当前网络状态：%@",trip]];
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

- (UIViewController *)getKeyWindowRootViewController {
    
//    CETabBarController *vc = [CETabBarController sharedTabBarController];
//    vc.hidesBottomBarWhenPushed = YES;
    return appDelegate.window.rootViewController;
}

//网络请求
+ (BOOL)saveResponseData:(NSDictionary *)data toPath:(NSString *)requestPath{
    if ([self createDirInCache:kPath_ResponseCache]) {
        NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
        BOOL succeed = [NSKeyedArchiver archiveRootObject:data toFile:abslutePath];
        if (!succeed) {
            NSLog(@"requestPath write failuer");
        }
        return succeed;
    }else{
        return NO;
    }
}
+ (id) loadResponseWithPath:(NSString *)requestPath{//返回一个NSDictionary类型的json数据
    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:abslutePath];
}

+ (BOOL)deleteResponseCacheForPath:(NSString *)requestPath{
    NSString *abslutePath = [NSString stringWithFormat:@"%@/%@.plist", [self pathInCacheDirectory:kPath_ResponseCache], [requestPath md5Str]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:abslutePath]) {
        return [fileManager removeItemAtPath:abslutePath error:nil];
    }else{
        return NO;
    }
}

+ (BOOL) deleteResponseCache{
    return [self deleteCacheWithPath:kPath_ResponseCache];
}

+ (BOOL) deleteCacheWithPath:(NSString *)cachePath{
    NSString *dirPath = [self pathInCacheDirectory:cachePath];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    bool isDeleted = false;
    if ( isDir == YES && existed == YES )
    {
        isDeleted = [fileManager removeItemAtPath:dirPath error:nil];
    }
    return isDeleted;
}

#pragma mark File M
//获取fileName的完整地址
+ (NSString* )pathInCacheDirectory:(NSString *)fileName
{
    NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cachePaths objectAtIndex:0];
    return [cachePath stringByAppendingPathComponent:fileName];
}
//创建缓存文件夹
+ (BOOL) createDirInCache:(NSString *)dirName
{
    NSString *dirPath = [self pathInCacheDirectory:dirName];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    BOOL isCreated = NO;
    if ( !(isDir == YES && existed == YES) )
    {
        isCreated = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (existed) {
        isCreated = YES;
    }
    return isCreated;
}

- (NSString *)JsonSting{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

- (void)telphoneWithNumber:(NSString *)phone{
        
    if ([[UIDevice currentDevice].systemVersion floatValue]<10.0) {
        [NSObject.getKeyWindowRootViewController gq_presentAlertControllerTitle:nil message:phone actionTitles:@[@"取消",@"拨打"] handler:^(NSInteger index) {
            if (index==1) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];
            }
        }];
        
    }else{
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@",phone]] options:@{} completionHandler:nil];
        } else {
            // Fallback on earlier versions
        }
    }
    
}

- (void)alertWithMsg:(NSString *)msg sureBtnTitle:(NSString *)sureTitle cancelBtnTitle:(NSString *)cancelTitle sureHander:(void (^ __nullable)(UIAlertAction *action))sureHander cancelHander:(void (^ __nullable)(UIAlertAction *action))cancelHander{
    UIAlertController *controller=[UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *act1=[UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:sureHander];
    [act1 setValue:UIColor.blueColor forKey:@"titleTextColor"];
    [controller addAction:act1];
    if (!IsStrEmpty(cancelTitle)) {
        UIAlertAction *act2=[UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleDefault handler:cancelHander];
        [act2 setValue:rgb(89, 89, 89) forKey:@"titleTextColor"];
        [controller addAction:act2];
        
    }
    [appDelegate.window.rootViewController presentViewController:controller animated:YES completion:^{
    }];
}


+ (BOOL)SystemSelector:(SEL)systemSelector swizzledSelector:(SEL)swizzledSelector error:(NSError *)error{

    Method systemMethod = class_getInstanceMethod(self, systemSelector);
    if (!systemMethod) {
        return NO;
    }

    Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    if (!swizzledMethod) {

        return NO;
    }

    if (class_addMethod([self class], systemSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {

        class_replaceMethod([self class], swizzledSelector, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
    }else{
        method_exchangeImplementations(systemMethod, swizzledMethod);
    }

    return YES;
}

@end
